//
//  ExpressDetailViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/9/1.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "ExpressDetailViewController.h"
#import "ExpressDetailEditingViewController.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "ExpressDetail.h"
#import "ExpressDetailedCell.h"
#import "ExpressDetailingCell.h"
#import "SendSMSTime.h"

@interface ExpressDetailViewController ()<SocketRequestDelegate> {
    SocketRequest *_socketRequest;
    ExpressDetail *_expressDetail;
    SendSMSTime *_sendSMSTime;
    
    BOOL _isWaitLuru;//判断是否是待录入
}

@end

@implementation ExpressDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"运单详情";
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateExpressMessage) name:@"updateexpresssuccess" object:nil];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 10)];
    NSString *sql = [NSString stringWithFormat:@"WHERE inwayExpressId = '%@'",self.inwayExpressId];
    _sendSMSTime = [SendSMSTime findFirstByCriteria:sql];
    [self getExpressDetailSocket];
}

- (void)updateExpressMessage {
    if (_isWaitLuru) {
        _isWaitLuru = NO;
        if ([_delegate respondsToSelector:@selector(updateExpress:Telephone:Address:Position:)]) {
            [_delegate updateExpress:self.indexPath Telephone:_expressDetail.telephone Address:_expressDetail.address Position:_expressDetail.position];
        }
    } else {
        if ([_delegate respondsToSelector:@selector(updateExpress:Telephone:Address:)]) {
            [_delegate updateExpress:self.indexPath Telephone:_expressDetail.telephone Address:_expressDetail.address];
        }
    }
}

#pragma socketmethod
- (void)getExpressDetailSocket {
    if (!_expressDetail) {
        [self.tableView makeLoading];
    } else {
        [self.tableView makeNone];
    }
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STS9"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:self.inwayExpressId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

- (void)resetSendCodeSocket {
    [ToastActivity makeActivity:@"短信发送中..." InView:self.view];
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STSB"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:self.inwayExpressId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:2];
}

- (void)sureReceiveExpressSocket {
    [ToastActivity makeActivity:@"确认签收中..." InView:self.view];
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STS6"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.userId] length:64];
    NSString *content = [NSString stringWithFormat:@"3,%@,3",self.inwayExpressId];
    NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
    [mutableData appendData:[SocketMethod hexDataWithLength:contentData.length]];
    [mutableData appendData:contentData];
    [_socketRequest addSocketData:mutableData SocketTag:3];
}

- (void)reloadTableView {
    self.tableView.backgroundView = nil;
    if ([_expressDetail.expressType isEqualToString:@"0033"] || [_expressDetail.expressType isEqualToString:@"0007"] || [_expressDetail.expressType isEqualToString:@"0015"] || [_expressDetail.expressType isEqualToString:@"0029"]) {
        self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 0.1)];
    } else if ([_expressDetail.expressType isEqualToString:@"0031"] || [_expressDetail.expressType isEqualToString:@"0005"]) {//待配送
        _visitFooterView.frame = CGRectMake(0, 0, 320, 170);
        self.tableView.tableFooterView = _visitFooterView;
    } else {
        _zitiFooterView.frame = CGRectMake(0, 0, 320, 120);
        self.tableView.tableFooterView = _zitiFooterView;
    }
    [self reloadSMSTime];
    [self.tableView reloadData];
}

- (void)reloadSMSTime {
    if (_sendSMSTime) {
        if (self.tableView.tableFooterView == _zitiFooterView) {
            _sendTimeLabel.text = [NSString stringWithFormat:@"最近一次发送时间:%@",_sendSMSTime.sendTime];
        } else if (self.tableView.tableFooterView == _visitFooterView) {
            _newSendTimeLabel.text = [NSString stringWithFormat:@"最近一次发送时间:%@",_sendSMSTime.sendTime];
            sureBtn.frame = CGRectMake(sureBtn.frame.origin.x, sureBtn.frame.origin.y + 5, sureBtn.frame.size.width, sureBtn.frame.size.height);
        }
    }
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_expressDetail) {
        return 1;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([_expressDetail.expressType isEqualToString:@"0033"] || [_expressDetail.expressType isEqualToString:@"0007"] || [_expressDetail.expressType isEqualToString:@"0015"] || [_expressDetail.expressType isEqualToString:@"0029"]) {
        return 240;
    }
    return 200.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([_expressDetail.expressType isEqualToString:@"0033"] || [_expressDetail.expressType isEqualToString:@"0007"] || [_expressDetail.expressType isEqualToString:@"0015"] || [_expressDetail.expressType isEqualToString:@"0029"]) {
        static NSString *CellIndentifier = @"ExpressDetailedCell";
        ExpressDetailedCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ExpressDetailedCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell reloadExpressDetailedCell:_expressDetail];
        return cell;
    } else {
        static NSString *CellIndentifier3 = @"ExpressDetailingCell";
        ExpressDetailingCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier3];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ExpressDetailingCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell reloadExpressDetailingCell:_expressDetail];
        return cell;
    }
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    if (socket.socketTag == 1) {
        if ([code isEqualToString:SuccessSocket]) {
            NSString *content = [SocketMethod stringDecryHexData:data];
            NSArray *array = [content componentsSeparatedByString:@"|"];
            for (NSString *string in array) {
                if (string.length > 0) {
                    _expressDetail = [[ExpressDetail alloc] initWithString:string];
                    if (_expressDetail.telephone.length <= 0) {
                        _isWaitLuru = YES;
                    }
                    break;
                }
            }
            DLog(@"content:%@....%@",content,_expressDetail.expressType);
            [self reloadTableView];
        } else {
            [self.tableView makeTip:msg];
        }
    } else if (socket.socketTag == 2) {
        if ([code isEqualToString:SuccessSocket]) {
            _expressDetail.smsType = 0;
            if ([_delegate respondsToSelector:@selector(smsSendSuccess:)]) {
                [_delegate smsSendSuccess:self.indexPath];
            }
            [self.tableView reloadData];
            if (_sendSMSTime) {
                _sendSMSTime.sendTime = [self getCurrentTime];
            } else {
                _sendSMSTime = [[SendSMSTime alloc] init];
                _sendSMSTime.inwayExpressId = self.inwayExpressId;
                _sendSMSTime.sendTime = [self getCurrentTime];
            }
            [_sendSMSTime saveOrUpdate];
            [self reloadSMSTime];
            [ToastActivity makeSuccess:@"短信已发送" InView:self.view];
        } else {
            [ToastActivity makeError:msg InView:self.view];
        }
    } else if (socket.socketTag == 3) {
        if ([code isEqualToString:SuccessSocket]) {
            _expressDetail.expressType = @"0033";
            if ([_delegate respondsToSelector:@selector(takeExpressSuccess:)]) {
                [_delegate takeExpressSuccess:self.indexPath];
            }
            [ToastActivity makeSuccess:@"签收成功" InView:self.view];
            [self reloadTableView];
        } else {
            [ToastActivity makeError:msg InView:self.view];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    if (socket.socketTag == 1) {
        [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getExpressDetailSocket)];
        [DSToast showText:msg InView:self.view];
    } else if (socket.socketTag == 2) {
        [ToastActivity makeError:msg InView:self.view];
    } else if (socket.socketTag == 3) {
        [ToastActivity makeError:msg InView:self.view];
    }
}

//获取时间
- (NSString *)getCurrentTime {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    return [dateFormatter stringFromDate:[NSDate date]];
}

#pragma mark NibAction
- (IBAction)changeExpress:(id)sender {
    [MobClick event:@"mingxi_btn_xiugaiyundan"];
    ExpressDetailEditingViewController *expressDEVC = [[ExpressDetailEditingViewController alloc] initWithNibName:@"ExpressDetailEditingViewController" bundle:nil];
    expressDEVC.express = _expressDetail;
    [self.navigationController pushViewController:expressDEVC animated:YES];
}

- (IBAction)resetSendCode:(id)sender {
    if (_expressDetail.telephone.length > 0) {
        [MobClick event:@"mingxi_btn_chongfaqujianma"];
        [self resetSendCodeSocket];
    } else {
        [DSToast showText:@"该快件没有收件人手机号" InView:self.tableView];
    }
}

- (IBAction)sureReceiveExpress:(id)sender {
    [self sureReceiveExpressSocket];
}

- (void)dealloc {
    _socketRequest = nil;
    _expressDetail = nil;
    _sendSMSTime = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"updateExpressMessage" object:nil];
}

@end
